﻿var app = {};
app.urlHelper = function (base) {
    var url = "https://" + base + "firebaseio.com/";
        for (var i = 1; i < arguments.length; ++i) {
        url += arguments[i] + "/";
    }
    url += ".json"
    return url;
}

app.ajax = function (method, url, data, success, error) {
    var request = new XMLHttpRequest();
    request.open(method, url, false);
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            success(JSON.parse(this.response))
        } else {
            console.log("Error " + method); // putting the method here will give you an idea on where it failed
            error();
        }
    };
    request.onerror = function () {
        console.log("Communication Error!");
        error();
    };
    if (data) {
        request.send(JSON.stringify(data));
    } else {
        request.send();
    }
};

var error = function () {
    console.log("error");

};

var success = function () {
    console.log("success");
};

var message = { message: "hey" };
app.ajax("POST", app.urlHelper("brilliant-fire-2547"), messages, success, error);

success = function (data) {
    console.log(data);
    for (var i in data) {
        key = i;
    }
}
app.ajax("GET", app.urlHelper("brilliant-fire-2547"), null, success, error);
//app.ajax("DELETE", app.urlHelper, ("brilliant-fire-2547", null, key), null, function () { console.log("success"); },
//    function () {
//        console.log("error");
//    });

message = { message: "change" };
app.ajax("PATCH", app.urlHelper("9er", "messages", key), message, success, error);